﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace WeChatTool
{
	public   class FileUtil
	{


		[DllImport("shfolder.dll", CharSet = CharSet.Auto)]
		private static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);
		private const int MAX_PATH = 260;
		private const int CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019;
		
		/// <summary>
		/// 获得所有用户桌面
		/// </summary>
		/// <returns></returns>
		public static string GetAllUsersDesktopFolderPath()
		{
			StringBuilder sbPath = new StringBuilder(MAX_PATH);
			SHGetFolderPath(IntPtr.Zero, CSIDL_COMMON_DESKTOPDIRECTORY, IntPtr.Zero, 0, sbPath);
			return sbPath.ToString();
		}


		/// <summary>
		/// 获得微信主程序路径
		/// </summary>
		/// <returns></returns>
		public static string GetWeChatPath()
		{
			if (File.Exists(Properties.Settings.Default.WeChat))
			{
				return Properties.Settings.Default.WeChat;
			}
			else
			{
				string path0 = FileUtil.GetAllUsersDesktopFolderPath();
				string path1 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
				string path2 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.StartMenu);//开始菜单项
				string path3 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Startup);
				//string path4 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Recent);//只记录文档，运行的程序记录没有记录
				string path5 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Programs);//开始最菜单的程序

				string[] xx = new string[] { path0, path1, path2, path3, path5 };
				foreach (var item in xx)
				{
					try
					{
						var lnks = Directory.GetFiles(item, "*.lnk", SearchOption.AllDirectories);
						var shortcutInfo = lnks.FirstOrDefault(x => x.EndsWith("微信.lnk")).ReadShortcut();
						if (!(shortcutInfo is null) && shortcutInfo.TargetPath.EndsWith("WeChat.exe", StringComparison.CurrentCultureIgnoreCase))
						{
							return shortcutInfo?.TargetPath;
						}
					}
					catch (Exception)
					{
						Console.WriteLine(item);
					}
				}
				return string.Empty;
			}
		}



		/// <summary>
		/// 获取微信接收文件目录
		/// </summary>
		/// <returns></returns>
		public static string GetFolder(string wechatPath="")
		{
			if (Directory.Exists(Properties.Settings.Default.Folder))
			{
				return Properties.Settings.Default.Folder;
			}
			else
			{
				var userDir = find(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
				if (userDir == null) {
					if (string.IsNullOrEmpty(wechatPath))
					{ return string.Empty; }
					else
						return find(wechatPath)??string.Empty;
				}
				return Path.Combine(userDir, "FileStorage", "File");
			}
		}

		static string find(string path)
		{
			var wxDir = Path.Combine(path, "WeChat Files");
			if (!Directory.Exists(wxDir)) { return string.Empty; }
			string[] ex = new string[] { "All Users", "Applet", "WMPF" };
			var userDir = Directory.EnumerateDirectories(wxDir)
				.Select(x => new FileInfo(x)).Where(x => !ex.Contains(x.Name))
				.OrderByDescending(x => x.LastAccessTime).FirstOrDefault()?.FullName;
			return userDir;
		}


		/// <summary>
		/// 按目录批量取消文件只读
		/// </summary>
		/// <param name="dir"></param>
		/// <returns></returns>
		public static int BatchCancelReadOnly(string dir)
		{
			try
			{
				var files = Directory.GetFileSystemEntries(dir, "*.*", searchOption: SearchOption.AllDirectories);
				var readOnlyfiles = files.Where(x => File.GetAttributes(x).ToString().IndexOf("ReadOnly") != -1).ToArray(); //只读文件
				foreach (var file in readOnlyfiles)
				{
					File.SetAttributes(file, FileAttributes.Normal);
				}
				return readOnlyfiles.Length;
			}
			catch (Exception)
			{
				return 0;
			}
		}

		/// <summary>
		/// 取消文件只读
		/// </summary>
		/// <param name="dir"></param>
		/// <returns></returns>
		public static bool CancelReadOnly( string path)
		{
			if (File.Exists(path) && File.GetAttributes(path).ToString().IndexOf("ReadOnly") != -1)
			{
				File.SetAttributes(path, FileAttributes.Normal);
				return true;
			}
			else { return false; }

		}
	}
}
